import QtQuick
import QtQuick.Controls

Rectangle {
    id: serialConnectRect
    width: 200
    height: 400
    color: "#1f2428"

    signal actionErrorTips(var tips)

    property color mTextColor: "#e1e4e8"
    property int mTextSize: 13

    function setSerialData() {
        serialPort.model = user.getMyProperty("serialCOM")
        serialDescription.text = user.getMyProperty("serialDes", serialPort.currentIndex)
    }

    Component.onCompleted: {
        setSerialData()
    }

    Connections {
        target: serial

        function onSerialScanCompleted() {
            setSerialData()
        }

        function onSerialOpened() {
            connectBtn.text = qsTr("断开")
        }

        function onSerialOpenFailed() {
            connectBtn.text = qsTr("连接")
        }

        function onSerialClosed() {
            connectBtn.text = qsTr("连接")
        }
    }

    Connections {
        target: serialEvent

        function onComDevArriaval(devName) {
            user.beginSerialScan()
        }

        function onComDevRemoveComplete(devName) {
            if(devName === serialPort.currentText) {
                if(connectBtn.text === qsTr("断开")) {
                    user.closeSerialPort()
                    actionErrorTips(qsTr("当前打开的串口被意外中断"))
                }
            }
            user.beginSerialScan()
        }
    }

    Column {
        anchors.fill: parent
        spacing: 5

        Row {
            width: parent.width
            height: 30

            AsText {
                height: parent.height
                text: qsTr("端口号")
                font.pixelSize: mTextSize
                color: mTextColor
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignLeft
            }

            AsComboBox {
                id: serialPort
                width: 100
                height: parent.height
                model: ["COM1"]
                textSize: mTextSize
                backDisplay: true

                onCurrentIndexChanged: {
                    serialDescription.text = user.getMyProperty("serialDes", currentIndex)
                }
            }
        }

        AsText {
            id: serialDescription
            width: parent.width
            text: qsTr("无")
            font.pixelSize: mTextSize - 1
            color: mTextColor
            verticalAlignment: Text.AlignVCenter
            horizontalAlignment: Text.AlignLeft
        }

        AsButton {
            id: connectBtn
            x: (parent.width - width) / 2
            width: 100
            height: 30
            text: qsTr("连接")
            font.pixelSize: mTextSize
            itemRadius: 8

            onClicked: {
                if(text === qsTr("连接")) {
                    user.openSerialPort(serialPort.currentText)
                } else if(text === qsTr("断开")) {
                    user.closeSerialPort()
                }
            }
        }
    }
}
